//
//  Migration.swift
//  hello
//
//  Created by 赵康 on 2025/3/30.
//


// NoteReviewMigration.swift

import Fluent

extension NoteReview {
    struct Migration: AsyncMigration {
        var name: String { "CreateNoteReview" }
        
        func prepare(on database: Database) async throws {
            try await database.schema(SchemaEnum.noteReviews.rawValue)
                .id()
                .field(FieldKeys.note, .uuid, .references(SchemaEnum.notes.rawValue, .id, onDelete: .cascade))
                .field(FieldKeys.user, .uuid, .references(SchemaEnum.users.rawValue, .id, onDelete: .cascade))
                .field(FieldKeys.difficulty, .string, .required)
                .field(FieldKeys.nextReviewDate, .datetime)
                .field(FieldKeys.reviewCount, .int, .required, .sql(.default(0)))
                .field(FieldKeys.lastReviewDate, .datetime)
                
                .field(FieldKeys.createdAt, .datetime)
                .field(FieldKeys.updatedAt, .datetime)
                .unique(on: FieldKeys.note, FieldKeys.user)
                .create()
        }
        
        func revert(on database: Database) async throws {
            try await database.schema(SchemaEnum.noteReviews.rawValue).delete()
        }
    }
}

// 如果已有现有数据，添加更新迁移
extension NoteReview {
    struct AddAnkiAlgorithmFields: AsyncMigration {
        var name: String { "AddAnkiAlgorithmFields" }
        
        func prepare(on database: Database) async throws {
            try await database.schema(SchemaEnum.noteReviews.rawValue)
                .field(FieldKeys.easeFactor, .double, .required, .sql(.default(2.5)))
                .field(FieldKeys.interval, .double, .required, .sql(.default(0)))
                .field(FieldKeys.learningStage, .string, .required, .sql(.default("new")))
                .field(FieldKeys.lapseCount, .int, .required, .sql(.default(0)))
                .update()
        }
        
        func revert(on database: Database) async throws {
            try await database.schema(SchemaEnum.noteReviews.rawValue)
                .deleteField(FieldKeys.easeFactor)
                .deleteField(FieldKeys.interval)
                .deleteField(FieldKeys.learningStage)
                .deleteField(FieldKeys.lapseCount)
                .update()
        }
    }
}



